package com.jwater.console.common;

import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @description: 切面，打印所有的接口请求信息
 * @author: jnner
 * @createDate: 2021/2/5
 * @version: 1.0
 */
@Aspect
@Component
public class ControllerAspect {
    private static final Logger log = LoggerFactory.getLogger(ControllerAspect.class);
    private static final String CRLF = "[\r\n]";

    @Pointcut("execution(* com.jwater.console.controller.*.*(..))")
    public void execute() {
    }

    @Before("execute()")
    public void before(JoinPoint joinPoint) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        if (servletRequestAttributes == null) {
            return;
        }
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String uri = request.getRequestURI().replace(CRLF, "");
        String args = Arrays.toString(joinPoint.getArgs()).replace(CRLF, "");
        if (args.length() > 1000) {
            args = args.substring(0, 1000);
        }
        log.info("path:{},params:{}", uri.replaceAll("[\r\n]", ""), args.replaceAll("[\r\n]", ""));
    }
}
